<?php

namespace App\Admin\Controllers;

use App\Admin\Grid\Tools\BatchDispatchForm;
use App\Admin\Renderable\DispatchUser;
use App\Models\UserGroup;
use App\Models\XXlBaseForm;
use Carbon\Carbon;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Illuminate\Support\Str;

class XXlBaseFormController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '信息流线索汇总';

    public function hasNewForm()
    {
        $user = Admin::user();
        $date = request()->get('date');
        $exists = $user->baseForm()->whereDate('created_at', $date)
            ->exists();
        return response()
            ->json([
                'status' => 1,
                'exists' => $exists,
            ]);
    }

    /**
     * Get content title.
     *
     * @return string
     */
    protected function title()
    {
        $title = request()->get('__title__');

        return $title ?: ($this->title ?: admin_trans_label());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $formModel = XXlBaseForm::query()
            ->with(['user', 'group'])
            ->orderBy('created_at', 'DESC');

        $user = Admin::user();

        $groupSet = explode(',', request()->get('__group_id__', ''));

        if (!$user->can('base_form.all')) {
            if ($user->can('base_form.group') && $groupSet) {
                $groupId = $user->group->pluck('id');
                $groupSet = collect($groupSet)->diff($groupId)->toArray();
            } else {
                $formModel->whereHas('user', function ($q) use ($user) {
                    $q->where('user_id', $user->id);
                });
            }
        }
        if ($groupSet)
            $formModel->whereIn('group_id', $groupSet);

        return Grid::make($formModel, function (Grid $grid) use ($groupSet) {
            $grid->disableCreateButton();
            $grid->export()->xlsx();

            $grid->filter(function (Grid\Filter $filter) use ($groupSet) {
                // 更改为 rightSide 布局
                $filter->rightSide();

                $filter->like('channel', '渠道');
                $filter->like('phone', '电话');
                $filter->like('remark', '备注');
                if ($groupSet && count($groupSet) > 1) {
                    $groupQuery = UserGroup::query()->whereIn('id', $groupSet);

                    $filter->equal('group_id', '所属分组')
                        ->select($groupQuery->pluck('name', 'id'));
                }

                $filter->like('url', '表单链接');

                $filter->between('created_at', '创建时间')->datetime([
                    'startOptions' => [
                        'defaultCurrent' => Carbon::today()->toDateString() . ' 00:00:00',
                    ],
                    'endOptions' => [
                        'defaultCurrent' => Carbon::today()->toDateString() . ' 23:59:59',
                    ],
                ]);
            });

            $grid->disableViewButton();
            if (!Admin::user()->can('base_form.delete')) {
                $grid->disableDeleteButton();
                $grid->disableBatchDelete();
            }
            if (!Admin::user()->can('base_form.update')) {
                $grid->disableEditButton();
            }

            $grid->fixColumns(3, 0);
            if (Admin::user()->can('base_form.dispatch'))
                $grid->batchActions([new BatchDispatchForm()]);

            $grid->column('created_at', __('时间'));

            $grid->column('_user', __('所属人员'))
                ->display(function () {
                    return $this->user->first()['name'] ?? '-';
                })
                ->if(function () {
                    return Admin::user()->can('base_form.dispatch');
                })
                ->superModal(function ($event) {
                    $event->icon('');
                    $event->title('123');
                    $id = data_get($this->user->first(), 'id');

                    return DispatchUser::make()->payload([
                        'id' => $this->id,
                        'user_id' => $id,
                        'group_id' => $this->group_id
                    ]);
                });

            $grid->column('name', __('客户姓名'));

            $grid->column('phone', __('客户电话'))
                ->copyable();
            $grid->column('channel', __('线索渠道'))
                ->display(function ($val) {
                    return $val ?? '-';
                });
            $grid->column('question_data', __('客户问题'))
                ->style('min-width:200px;');
            $grid->column('url', __('表单链接'))
                ->display(function ($val) {
                    return urldecode($val);
                })
                ->setAttributes([
                    'style' => 'max-width: 200px;white-space: normal;word-break: break-all;min-width:150px;'
                ])
                ->copyable();

            $grid->column('city', __('城市'))->display(function ($city) {
                return $this->state_name . $city;
            })->label();
            $grid->column('remark', '备注')
                ->style('min-width:150px;')
                ->newEditable();
            $grid->column('group.name', '分组')->display(function ($val) {
                return $val ?: "-";
            });
            $grid->column('leads_id', "ID");

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(XXlBaseForm::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('name', __('Name'));
        $show->field('phone', __('Phone'));
        $show->field('channel', __('Channel'));
        $show->field('question_data', __('Question data'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    public function destroy($id)
    {
        return $this->form()->destroy($id);
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {

        return Form::make(new XXlBaseForm, function (Form $form) {
            $form->text('name', __('Name'));
            $form->mobile('phone', __('Phone'));
            $form->text('channel', '渠道');
            $form->text('url', '表单链接');
            $form->text('remark', '备注');
            $form->select('group_id', '分组')
                ->options(UserGroup::all()->pluck('name', 'id'));
        });

    }
}
